package com.trade.common.scheduler;

import com.trade.module.database.operation.DBDataQueryCallback;
import com.trade.module.database.operation.DBDataQueryLoigic;
import com.trade.module.frontEndServer.FrontEndDBVo;
import lombok.extern.log4j.Log4j;

import java.util.Date;

/**
 * Class Description: 数据库任务处理类
 *
 * @Version v1.0 2017/12/7 21:45
 * @JDK version 1.8.0_51
 * @Author zfb
 */
@Log4j
public class DBWorkHandler implements WorkHandler {

    /**
     * 开始任务
     * @param frontEndDBVo 启动任务的参数类（前置机）
     * @param clientWorkCallback 任务执行回调
     * @return
     * @throws Exception
     */
    @Override
    public String startTask(Object frontEndDBVo, ClientWorkCallback clientWorkCallback) throws Exception {
        //获取任务管理器
        ClientWorkManager clientWorkManager = ClientWorkManager.getInstance();
        if(frontEndDBVo instanceof FrontEndDBVo){
            FrontEndDBVo frontEndDBVoTemp = (FrontEndDBVo) frontEndDBVo;
            String workId = clientWorkManager.createClientWork(frontEndDBVoTemp, clientWorkCallback);
            //判断定时任务是否需要立即执行一次
            Integer executeImmediately = frontEndDBVoTemp.getExecuteImmediately();
            if (executeImmediately != null && executeImmediately > 0) {
                clientWorkManager.schedule(workId,
                        new ClientTask() {
                            @Override
                            public void run() {
                                executeTask(getClientTaskCallback(), frontEndDBVoTemp, workId);
                            }
                        }
                        , 0);
            }
            //判断定时任务是否需要定时执行需求
            Date firstExecuteTime = frontEndDBVoTemp.getFirstExecuteTime();
            Long intervalTime = frontEndDBVoTemp.getIntervalTime();
            if (firstExecuteTime != null) {
                if (intervalTime != null && intervalTime > 0) {
                    //定时执行并循环执行任务
                    clientWorkManager.scheduleAtFixedRate(workId,
                        new ClientTask() {
                            @Override
                            public void run() {
                                executeTask(getClientTaskCallback(), frontEndDBVoTemp, workId);
                            }
                        }
                        , firstExecuteTime, intervalTime);
                } else {
                    //定时执行不循环执行任务
                    clientWorkManager.schedule(workId,
                        new ClientTask() {
                            @Override
                            public void run() {
                                executeTask(getClientTaskCallback(), frontEndDBVoTemp, workId);
                            }
                        }
                        , firstExecuteTime);
                }
            }
        }
        return null;
    }

    /**
     * 任务执行
     * @param clientTaskCallback 任务回调
     * @param frontEndDBVo 前置机对象
     * @param workId 任务id
     */
    private void executeTask(ClientTaskCallback clientTaskCallback, FrontEndDBVo frontEndDBVo, String workId) {
        try {
            DBDataQueryLoigic dbDataQueryLoigic = new DBDataQueryLoigic(frontEndDBVo);
            dbDataQueryLoigic.setDbDataQueryCallback(new DBDataQueryCallback() {
                @Override
                public void dataFinished(FrontEndDBVo frontEndDBVoTemp) {
                    clientTaskCallback.taskFinished(new TaskResultVo("", frontEndDBVo));
                    //关闭DatabaseSource
//                    try {
//                        dbDataQueryLoigic.closeDataSource();
//                    } catch (SQLException e) {
//                        e.printStackTrace();
//                    }
                }

                @Override
                public void dataPartial(FrontEndDBVo frontEndDBVoTemp) {
                    clientTaskCallback.taskPartialData(new TaskResultVo("", frontEndDBVoTemp));
                }

                @Override
                public void dataQueryException(Exception e, FrontEndDBVo frontEndDBVoTemp) {
                    log.error("任务执行异常："+e+"，前置机详情："+frontEndDBVoTemp);
                }
            });
            dbDataQueryLoigic.startQuery(workId);
        } catch (Exception e) {
            log.error("DBWorkHandler执行异常", e);
        }
    }

    /**
     * 暂停任务
     * @param taskId 任务id
     * @return
     * @throws Exception
     */
    @Override
    public int pauseTask(String taskId) throws Exception {
        return 0;
    }

    /**
     * 继续执行任务
     * @param taskId 任务id
     * @return
     * @throws Exception
     */
    @Override
    public int resumeTask(String taskId) throws Exception {
        return 0;
    }

    /**
     * 停止任务
     * @param taskId 任务id
     * @return
     * @throws Exception
     */
    @Override
    public int stopTask(String taskId) throws Exception {
        return 0;
    }
}
